package com.cms.work.service.impl.sys;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cms.work.core.service.impl.BaseServiceImpl;
import com.cms.work.dao.sys.ISysResourceDao;
import com.cms.work.dao.sys.ISysUserDao;
import com.cms.work.entity.enums.CommonEnum.UserStatusEnum;
import com.cms.work.entity.sys.SysUser;
import com.cms.work.entity.sys.vo.ResetPasswordVO;
import com.cms.work.entity.sys.vo.SysRoleResourceVo;
import com.cms.work.exception.ExceptionCodeEnum;
import com.cms.work.exception.SystemException;
import com.cms.work.service.sys.ISysUserRoleService;
import com.cms.work.service.sys.ISysUserService;
import com.cms.work.util.CommonUtils;
import com.cms.work.util.StringUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @describe 用户管理模块 
 * @author YY
 * @version v1.0
 * @date 2016-11-22 13:42:36
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Integer> implements ISysUserService {
    
    private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private ISysUserDao sysUserDao;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysResourceDao sysResourceDao;

    @Override
    public void save(SysUser user) {
        if(user.getId() == null || user.getId() == 0){
            sysUserDao.insertSelective(user);
        }else{
            sysUserDao.updateByPrimaryKeySelective(user);
        }
    }

	@Override
	public SysUser addUser(SysUser sysUser, Integer[] roles) {
		sysUser.setCreateDate(new Date());
		sysUser.setSalt(CommonUtils.uuid());
		sysUser.setPassword(CommonUtils.md5("111111", sysUser.getSalt()));
		this.save(sysUser);
	    sysUserRoleService.addUserAndRoleLink(sysUser.getId(), roles);
		return sysUser;
	}

    @Override
    public void updateUserStatus(int userId, UserStatusEnum status) {
        SysUser user = new SysUser(userId, status.getStatus());
        this.updateSelective(user);
    }

    @Override
    public PageInfo<SysUser> selectPage(Map<String, Object> params) {
        PageInfo<SysUser> pageInfo = new PageInfo<SysUser>();
        String orderBy = (String) params.get("orderBy");
        if(StringUtils.isNotBlank(orderBy)){
            orderBy = orderBy+" "+params.get("orderDir");
            PageHelper.orderBy(orderBy);
        }
        
        int pageNum = (int) params.get("pageNum");
        int pageSize = (int) params.get("pageSize");
        PageHelper.startPage(pageNum, pageSize);
        
        SysUser entity = new SysUser();
        if("true".equals((String)params.get("fuzzySearch"))){
            String fuzzy = (String) params.get("fuzzy");
            if(StringUtils.isNotBlank(fuzzy)){
                entity.setUserName(fuzzy);
                entity.setLoginCode(fuzzy);
            }
            pageInfo = fuzzySelectPage(pageNum, pageSize, orderBy, entity);
        }else{
            entity = (SysUser) params.get("entity");
            pageInfo = selectPage(pageNum, pageSize, orderBy, entity);
        }
        
        return pageInfo;
    }

	@Override
	public List<SysRoleResourceVo> loadUserResource(Integer userId) {
		return sysResourceDao.getResourceByUserId(userId);
	}

	@Override
	public void resetPassword(ResetPasswordVO resetPassword) {
		SysUser user = sysUserDao.selectByPrimaryKey(resetPassword.getUserId());
		String oldPassword = CommonUtils.md5(resetPassword.getOldPassword(), user.getSalt());
		if(!StringUtil.checkPassword(user.getPassword(), oldPassword)){
			logger.error(user.getPassword() + " " + oldPassword + "密码不一致");
			throw new SystemException(ExceptionCodeEnum.SYS_USER_OLDPWD);
		}
		if(!StringUtil.checkPassword(resetPassword.getPassword(), resetPassword.getPassword2())){
			logger.error(resetPassword.getPassword() + " " + resetPassword.getPassword2() + "密码不一致");
			throw new SystemException(ExceptionCodeEnum.SYS_USER_PADDIFF);
		}
		user.setPassword(CommonUtils.md5(resetPassword.getPassword(), user.getSalt()));
		sysUserDao.updateByPrimaryKeySelective(user);
	}

}
